package org.tamal.jsf;

import java.io.IOException;

import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.tamal.HttpSession;
import org.tamal.persistence.User;

/**
 * This listener redirects to login page if the user is not logged in.
 *
 * @author Tamal Kanti Nath
 */
public final class AuthenticationListener implements PhaseListener {

    private static final long serialVersionUID = -8938736370598958565L;
    private static final String LOGIN = "/faces/login.xhtml";

    @Override
    public void afterPhase(PhaseEvent event) {
        FacesContext context = event.getFacesContext();
        ExternalContext ext = context.getExternalContext();
        User user = (User) ext.getSessionMap().get(HttpSession.USER);
        String view = context.getViewRoot().getViewId();
        if (user != null || LOGIN.equals(view)) {
            return;
        }
        try {
            ext.redirect(LOGIN);
        } catch (IOException e) {
            Application application = context.getApplication();
            NavigationHandler navigation = application.getNavigationHandler();
            navigation.handleNavigation(context, null, "login");
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        // Nothing...
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

}
